#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>  
#include <fcntl.h>  
#include <limits.h>  
#include <sys/types.h>  
#include <sys/stat.h>  
#include <string.h>
#include <unistd.h>

#define FIFO_NAME "/tmp/com_fifo"  
#define BUFFER_SIZE 1024  
#define TEN_MEG (1024 * 1024 * 10)  

#define _LARGEFILE_SOURCE
#define _LARGEFILE64_SOURCE
#define _FILE_OFFSET_BITS 64


char do_copy_file(char *p_source, char *p_des, int pipe_fd)
{

int fd_source;
int fd_des;
int copy_times;
char buf_tmp[4096];
char send_buf[64];
char *p_buf;
long byte_counter;
long all_bytes;
byte_counter = 0;
int read_bytes;
double copy_finished;
struct stat stat_buf;
//int fstat(int filedes,struct stat *buf);

fd_source = open(p_source,O_RDONLY);
if(fd_source < 0)
{
printf("open 123.dat fail");
return 1;
}	
fstat(fd_source,&stat_buf);
all_bytes = stat_buf.st_size;
fd_des = open(p_des,O_WRONLY|O_CREAT,"0755");
p_buf = send_buf;
if(fd_des < 0)
printf("open 222.txt fail");
copy_times = 0;
do
{
read_bytes = 0;
if(access(p_source,0) != 0)
exit(1);
read_bytes = read(fd_source,buf_tmp,4096);
memset(send_buf,0,64);
//printf("read_bytes:%ldMB  whole_bytes:%ldMB",byte_counter/(1024*1024),all_bytes/(1024*1024));
sprintf(send_buf,"read_bytes:%5ldMB  whole_bytes:%5ldMB",byte_counter/(1024*1024),all_bytes/(1024*1024));

byte_counter += read_bytes;
copy_times++;

if(read_bytes > 0)
{
write(fd_des,buf_tmp,read_bytes);
//printf("pipe bytes:%d\n",strlen(p_buf));
if(copy_times > 2048)
{
write(STDOUT_FILENO, send_buf, strlen(send_buf));
copy_times = 0;
usleep(500000);
}
}

}while(read_bytes);
write(STDOUT_FILENO, send_buf, strlen(send_buf));

close(fd_source);
close(fd_des);

chmod(p_des,7*8*8+5*8+5);
sync();
return 0;

}


int main(int argc, char *argv[])  
{  
int pipe_fd;  
int res;  
int open_mode = O_WRONLY;  
int bytes = 0;  
char buffer[BUFFER_SIZE + 1]; 
char *p_source;
char *p_des;

if(argc < 3)
{
printf("please input valid arguments: 1,source 2, des\n");	
return 0;
} 
p_source = argv[1];
p_des = argv[2];
#if 0
if (access(FIFO_NAME, F_OK) == -1)  
{  
res = mkfifo(FIFO_NAME, 0777);  
if (res != 0)  
{  
fprintf(stderr, "Could not create fifo %s\n", FIFO_NAME);  
exit(EXIT_FAILURE);  
}  
}  

printf("Process %d opening FIFO O_WRONLY\n", getpid());  
pipe_fd = open(FIFO_NAME, open_mode);  
printf("Process %d result %d\n", getpid(), pipe_fd);  
#endif


res = do_copy_file(p_source, p_des, pipe_fd);
if(res)
printf("copy fail ....\n");  


//printf("Process %d finish\n", getpid());  
exit(EXIT_SUCCESS);  
}  
